import { CommonResult, UserLoginDto, UserService } from "@/api";
import { useUserStore } from "@/store";
import ws from "@/plugins/ws-socket.ts";

const userStore = useUserStore();

/**
 * 账号登录
 * @param userLoginDto
 */
export const login = async (userLoginDto: UserLoginDto) => {
  const res: CommonResult = await UserService.login(userLoginDto);
  console.log(res.message);
  console.log(res.data);
  if (res.code === 100) {
    userStore.initial(res.data as unknown as object);
    // 创建连接
    ws.connect(res.data as string);
  } else {
    // 失败
  }
  return { code: res.code, msg: res.message };
};

/**
 * 登出
 */
export const logout = async () => {
  const token = userStore.token;
  if (!token) return;
  const res = await UserService.logout();
  if (res.code === 100) {
    userStore.reset();
  } else {
    // 失败
  }
  return { code: res.code, msg: res.message };
};
